package com.sens.orderback.ui.widget;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.TextView;

import com.sens.orderback.R;


/**
 * Author:xishuang
 * Date:2017.08.01
 * Des:悬浮窗的布局
 */
public class FloatLayout extends TextView {
    private final WindowManager windowManager;
    private long startTime;
    private float downX;
    private float downY;
    private boolean isClick;
    private WindowManager.LayoutParams windowParams;
    private long endTime;
    private int screenWidth;
    private DisplayMetrics displayMetrics = new DisplayMetrics();

    public FloatLayout(Context context) {
        this(context, null);
    }

    public FloatLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setBackgroundResource(R.drawable.shape_oval_red);
        setText("已关闭");
        setGravity(Gravity.CENTER);
        setTextColor(Color.WHITE);
        windowManager = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        screenWidth = displayMetrics.widthPixels;
        setClickable(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = (int) dip2px(50);
        super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY));
    }

    public void toogle(boolean isON) {
        this.isON = isON;
        post(runnable);
    }

    private boolean isON;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (isON) {
                setBackgroundResource(R.drawable.shape_oval_green);
                setText("已开启");
            } else {
                setBackgroundResource(R.drawable.shape_oval_red);
                setText("已关闭");
            }
        }
    };

    private boolean canFloat;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!canFloat) {
            canFloat = true;
            SharedPreferences sharedPreferences = getContext().getSharedPreferences("float", Context.MODE_PRIVATE);
            if (!sharedPreferences.getBoolean("float", false)) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                if (editor != null) {
                    editor.putBoolean("float", true);
                    editor.commit();
                }
            }
        }
        // 获取相对屏幕的坐标，即以屏幕左上角为原点
        int x = (int) event.getRawX();
        int y = (int) event.getRawY();
        //下面的这些事件，跟图标的移动无关，为了区分开拖动和点击事件
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                startTime = System.currentTimeMillis();
                downX = event.getX();
                downY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                //图标移动的逻辑在这里
                float moveX = event.getX();
                float moveY = event.getY();
                // 如果移动量大于3才移动
                if (Math.abs(downX - moveX) > 3
                        && Math.abs(downY - moveY) > 3) {
                    // 更新浮动窗口位置参数
                    windowParams.x = (int) (x - downX);
                    windowParams.y = (int) (y - downY);
                    windowManager.updateViewLayout(this, windowParams);
                    startTime -= 200;
                    return false;
                }
                break;
            case MotionEvent.ACTION_UP:
                endTime = System.currentTimeMillis();
                //当从点击到弹起小于半秒的时候,则判断为点击,如果超过则不响应点击事件
                if ((endTime - startTime) > 200) {
                    isClick = false;
                } else {
                    isClick = true;
                }
                if (windowParams.x < screenWidth / 2 - getWidth() / 2) {
                    windowParams.x = 0;
                } else {
                    windowParams.x = screenWidth;
                }
                windowManager.updateViewLayout(this, windowParams);
                break;
        }
        //响应点击事件
        if (isClick && isEnabled() && isClickable()) {
            isClick = false;
            if (clickListener != null) clickListener.onClick(this);
        }
        return true;
    }

    private View.OnClickListener clickListener;

    @Override
    public void setOnClickListener(View.OnClickListener l) {
        clickListener = l;
    }

    /**
     * 将小悬浮窗的参数传入，用于更新小悬浮窗的位置。
     *
     * @param params 小悬浮窗的参数
     */
    public void setParams(WindowManager.LayoutParams params) {
        windowParams = params;
        windowParams.width = (int) dip2px(40);
        windowParams.height = (int) dip2px(40);
        windowParams.y -= dip2px(120);
    }

    public WindowManager.LayoutParams getParams() {
        return windowParams;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public float dip2px(float dpValue) {
        return dpValue * displayMetrics.density + 0.5f;
    }

    boolean isAttachedToWindow;

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        isAttachedToWindow = true;
    }

    @Override
    public boolean isAttachedToWindow() {
        boolean attached;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            attached = super.isAttachedToWindow();
        else attached = isAttachedToWindow;
        if (!attached) {
            ViewParent parent = getParent();
            if (parent != null) {
                if (parent instanceof ViewGroup) {
                    ((ViewGroup) parent).removeView(this);
                }
            }
        }
        return attached;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isAttachedToWindow = false;
    }
}